package com.xwolf.os.message;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.*;
import java.util.UUID;

/**
 * @author ming
 * @Description:
 * @create 2018-07-03 10:44 PM
 **/
@Service
public class ProducerSync {
    @Autowired
    private JmsTemplate jmsTemplate;

    @Value("response.queue")
    private String responseDestinationName;

    public void sendMsg(String destinationName, final String message) throws JMSException {

        System.out.println("---------------生产者发了一个消息：" + message);

        Destination destination = new ActiveMQQueue(responseDestinationName);

        TextMessage replyMsg = (TextMessage)jmsTemplate.sendAndReceive(destinationName, new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                TextMessage objMsg = session.createTextMessage(message);
                String correlationID = UUID.randomUUID().toString();
                System.out.println("correlationID:" + correlationID);
                objMsg.setJMSCorrelationID(correlationID);
                objMsg.setJMSReplyTo(destination);
                return objMsg;
            }
        });

        System.out.println(">>>>>>=receive the response" + replyMsg.getText());
    }
}
